import { Input, Button, Form, Modal, Upload, Image, Radio, message } from "antd";
import type { FormInstance, UploadProps, UploadFile, GetProp } from "antd";
import SvgIcon from "@/components/SvgIcon";
import { PlusOutlined, EditOutlined } from "@ant-design/icons";
import { useState, useEffect, PropsWithChildren } from "react";
import { randomName } from "@/util/index";
import { uploadImg } from "@/api/xhr/common/index";
import { checkEmailExists } from "@/api/xhr/user/index";
import type { RegisterUserInfo } from "@/api/xhr/user/type";
import EmailVerifyModal from "@/components/EmailVerifyModal";

const SetUserInfo: React.FC<
  PropsWithChildren<
    { initialValues: RegisterUserInfo } & {
      open: boolean;
      confirmLoading: boolean;
      callback: (...args: any[]) => void;
      showCancel?: (args: false) => void;
    }
  >
> = props => {
  const [formInstance, setFormInstance] = useState<FormInstance>();
  async function handleOk() {
    try {
      const values = await formInstance?.validateFields();
      
      // 检查邮箱是否已被使用（如果邮箱有变化）
      if (values.email !== props.initialValues.email) {
        const res = await checkEmailExists(values.email, props.initialValues.userId);
        if (res.data?.exists) {
          message.error("该邮箱已被其他账号使用，请更换邮箱");
          return;
        }
      }
      
      props.callback(values);
    } catch (error) {
      console.log("Failed:", error);
    }
  }
  return (
    <Modal
      title="修改信息"
      open={props.open}
      confirmLoading={props.confirmLoading}
      closeIcon={false}
      footer={
        <>
          {props.showCancel && (
            <Button
              key="back"
              onClick={() => {
                props.showCancel && props.showCancel(false);
              }}
            >
              取消
            </Button>
          )}
          <Button
            key="submit"
            type="primary"
            onClick={handleOk}
            loading={props.confirmLoading}
          >
            提交
          </Button>
        </>
      }
    >
      <CollectionCreateForm
        initialValues={props.initialValues}
        onFormInstanceReady={instance => {
          setFormInstance(instance);
        }}
      ></CollectionCreateForm>
    </Modal>
  );
};

interface CollectionCreateFormProps {
  initialValues: RegisterUserInfo;
  onFormInstanceReady: (instance: FormInstance<RegisterUserInfo>) => void;
}

const CollectionCreateForm: React.FC<CollectionCreateFormProps> = ({
  initialValues,
  onFormInstanceReady
}) => {
  const [form] = Form.useForm();
  const [previewImage, setPreviewImage] = useState<string>();
  const [previewOpen, setPreviewOpen] = useState(true);
  const [emailVerifyVisible, setEmailVerifyVisible] = useState(false);
  const [tempEmail, setTempEmail] = useState("");
  const [editingEmail, setEditingEmail] = useState(false);
  const [originalEmail, setOriginalEmail] = useState(initialValues.email || "");
  
  type FileType = Parameters<GetProp<UploadProps, "beforeUpload">>[0];
  const [fileList, setFileList] = useState<UploadFile[]>([
    {
      uid: "-1",
      name: "default.png",
      url: initialValues.avatar
    }
  ]);
  
  useEffect(() => {
    onFormInstanceReady(form);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const getBase64 = (file: FileType): Promise<string> =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => {
        return resolve(reader.result as string);
      };
      reader.onerror = error => reject(error);
    });

  const handlePreview: UploadProps["onPreview"] = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as FileType);
    }
    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };

  const handleUpload = async (file: any) => {
    const formdata = new FormData();
    formdata.append("file", file.file);
    const res = await uploadImg({
      formdata,
      onUploadProgress: (ev: any) => {
        // ev.loaded 当前已上传内容的大小，ev.total - 本次上传请求内容总大小
        const percent = (ev.loaded / ev.total) * 100;
        // 计算出上传进度，调用组件进度条方法
        file.onProgress({ percent });
      }
    });
    const FileList = [
      {
        uid: "-1",
        name: res.data.name,
        url: import.meta.env.VITE_APP_STATIC_BASEURL + res.data.url
      }
    ];
    setFileList(() => FileList);
    form.setFieldValue("avatar", FileList[0].url);
    return false;
  };
  
  const handleChange: UploadProps["onChange"] = ({ fileList: newFileList }) => {
    if (newFileList.length == 0) {
      setFileList(newFileList);
      form.setFieldValue("avatar", "");
    }
  };
  
  // 处理邮箱修改
  const handleEditEmail = async () => {
    if (editingEmail) {
      // 点击确定，先验证邮箱唯一性再打开验证码modal
      const email = form.getFieldValue("email");
      if (email && email !== originalEmail) {
        try {
          // 检查邮箱是否已被使用
          const res = await checkEmailExists(email, initialValues.userId);
          if (res.data?.exists) {
            message.error("该邮箱已被其他账号使用，请更换邮箱");
            return;
          }
          
          // 邮箱可用，打开验证码弹框
          setTempEmail(email);
          setEmailVerifyVisible(true);
        } catch (error) {
          console.error("检查邮箱失败:", error);
        }
      } else {
        // 如果邮箱没有变化，直接关闭编辑状态
        setEditingEmail(false);
      }
    } else {
      // 点击修改，进入编辑状态
      setEditingEmail(true);
    }
  };
  
  // 处理邮箱输入框失焦
  const handleEmailBlur = () => {
    if (editingEmail) {
      // 如果处于编辑状态且失焦，恢复原始值并退出编辑状态
      form.setFieldValue("email", originalEmail);
      setEditingEmail(false);
    }
  };
  
  // 验证码验证成功
  const handleVerifySuccess = () => {
    setEmailVerifyVisible(false);
    setEditingEmail(false);
    setOriginalEmail(tempEmail);
    // 表单值已经在输入时更新，不需要再次设置
  };
  
  // 取消验证
  const handleVerifyCancel = () => {
    setEmailVerifyVisible(false);
    // 如果取消，恢复原来的邮箱
    form.setFieldValue("email", originalEmail);
    setEditingEmail(false);
  };
  
  const uploadButton = (
    <button style={{ border: 0, background: "none" }} type="button">
      <PlusOutlined />
    </button>
  );
  
  return (
    <div className="flex w-full">
      <SvgIcon name="register" className="h-[320px] w-[320px]"></SvgIcon>
      <div className="w-full">
        <Form form={form} name="form_in_modal" initialValues={initialValues}>
          <Form.Item
            name="avatar"
            label="头像"
            rules={[
              {
                required: true,
                message: "请选取头像"
              }
            ]}
          >
            <>
              <Upload
                accept="image/*"
                listType="picture-card"
                className="avatar-uploader"
                fileList={fileList}
                onPreview={handlePreview}
                customRequest={handleUpload}
                onChange={handleChange}
              >
                {fileList.length >= 1 ? null : uploadButton}
              </Upload>
              {previewImage && (
                <Image
                  wrapperStyle={{ display: "none" }}
                  preview={{
                    visible: previewOpen,
                    onVisibleChange: visible => setPreviewOpen(visible),
                    afterOpenChange: visible => !visible && setPreviewImage("")
                  }}
                  src={previewImage}
                />
              )}
            </>
          </Form.Item>
          <div className="flex">
            <Form.Item
              className="mr-2"
              name="username"
              label="昵称"
              rules={[{ required: true, message: "请输入昵称" }]}
            >
              <Input placeholder="请输入你的昵称" className="mr-2" />
            </Form.Item>
            <Button
              onClick={() => {
                const user = randomName();
                form.setFieldValue("username", user);
              }}
            >
              随机
            </Button>
          </div>
          <div className="flex items-center">
            <Form.Item
              name="email"
              label="邮箱"
              className="flex-1"
              rules={[
                { type: "email", message: "请输入正确的邮箱" },
                { required: true, message: "请输入邮箱" }
              ]}
            >
              <Input 
                placeholder="请输入你的邮箱" 
                autoComplete="off" 
                disabled={!editingEmail && !!originalEmail}
                onBlur={handleEmailBlur}
                suffix={
                  !!originalEmail && (
                    <Button 
                      type={editingEmail ? "primary" : "link"} 
                      size="small"
                      onClick={handleEditEmail}
                      icon={editingEmail ? null : <EditOutlined />}
                      className={editingEmail ? "bg-blue-500 text-white hover:bg-blue-600" : "text-blue-500 hover:text-blue-600"}
                      onMouseDown={(e) => e.preventDefault()}
                    >
                      {editingEmail ? "确定" : "修改"}
                    </Button>
                  )
                }
              />
            </Form.Item>
          </div>
          <Form.Item
            label="性别"
            name="sex"
            rules={[{ required: true, message: "请选取你的性别" }]}
          >
            <Radio.Group>
              <Radio value={1} key={1}>
                男
              </Radio>
              <Radio value={0} key={0}>
                女
              </Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item
            name="userSignature"
            label={
              <div className="flex items-center">
                <span>个性签名</span>
                <EditOutlined className="ml-1 text-blue-500" />
              </div>
            }
          >
            <Input.TextArea
              placeholder="写点什么介绍一下自己吧..."
              autoSize={{ minRows: 2, maxRows: 4 }}
              maxLength={100}
              showCount
            />
          </Form.Item>
        </Form>
        
        {/* 邮箱验证Modal */}
        <EmailVerifyModal
          open={emailVerifyVisible}
          email={tempEmail}
          onCancel={handleVerifyCancel}
          onSuccess={handleVerifySuccess}
          type="update"
        />
      </div>
    </div>
  );
};

export default SetUserInfo;
